<template>
  <el-container>
    <!-- 顶部标题 -->
    <el-header class="customHeader fixed-header">
      <div class="topBar"></div>
      <div class="headerContent">
        <!-- 左侧：Logo + 分隔线 + 标题 -->
        <div class="headerLeft">
          <img src="@/assets/image/logo.jpg" class="logo"  alt=""/>
          <div class="headerDivider"></div>
          <div class="titleWrapper">
            <div class="mainTitle">讯航<span class="newsText">News</span></div>
            <div class="subTitle">——武大新闻整合平台</div>
          </div>
          <el-button type="primary" size="large" class="aiChatBtn" @click="router.push('/ai')">
              AI Chat
          </el-button>
        </div>

        <div class="headerRightGroup">
          <!-- 右侧：搜索框 -->
           
          <div class="headerRight">
            <el-input v-model="searchText" 
            placeholder="文章搜索" 
            class="searchInput" 
            clearable  
            @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button class="custom-search-btn" @click="handleSearch">
                  <!-- 搜索逻辑待写 -->
                  <img src="@/assets/image/搜索.png" class="search-icon" alt="搜索" />
                </el-button>
              </template>
            </el-input>
          </div>

          <!-- 新增管理员区域 -->
          <div class="adminArea">
            <el-button type="primary" size="large" class="adminBtn" @click="router.push('/login')">
              管理员登录
            </el-button>
            <img src="@/assets/image/admin.png" class="adminLogo" />
          </div>
        </div>
      </div>
    </el-header>

    <!-- 添加占位元素避免内容被遮挡 -->
    <div class="header-placeholder"></div>

    <el-main>
      <!-- 计院图 -->
      <!-- <div class="banner-image">
        <img src="../assets/image/R-C.jpg" alt="宣传横幅" style="width: 100%; height: 180px" />
      </div> -->
      <!-- 分类导航 -->
      <el-tabs v-model="activeCategory" class="customTabs" @tab-click="handleTabClick">
        <el-tab-pane label="新闻首页" name="home"></el-tab-pane>
        <el-tab-pane label="武大咨询" name="news"></el-tab-pane>
        <el-tab-pane label="珞珈人物" name="people"></el-tab-pane>
        <el-tab-pane label="信息发布" name="info" ></el-tab-pane>
        <el-tab-pane label="校园生活" name="life" ></el-tab-pane>
      </el-tabs>



        <div class="news-container">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="error" class="error">加载失败: {{ error }}</div>
          <div v-else class="news-list">
            <div v-for="(item, index) in filteredNews" :key="item.id" class="news-item" @click="intoDetailPage(item.id)">
              <div class="news-image">
                <img :src="item.images" :alt="item.title" v-if="item.images" />
                <div class="no-image" v-else>暂无图片</div>
              </div>
              <div class="news-content">
                <h2>{{ item.title }}</h2>
                <p class="summary">{{ item.summary }}</p>
                <div class="meta">
                  <span class="time">{{ formatDate(item.submitTime) }}</span>
                  <!-- <span class="views">浏览量: {{ item.pageviews }}</span> -->
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="custom-backtop" @click="scrollToTop" v-show="showBacktop">
          <el-icon :size="20"><Top /></el-icon>
        </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import {createRouter as $router, useRouter} from 'vue-router'
import { Top } from '@element-plus/icons-vue'
import axios from "axios";

// 定义响应式数据
const newsData = ref([]);
const filteredNews = ref([]);
const loading = ref(true);
const error = ref(null);

const router = useRouter()
const activeCategory = ref('home')
const observer = ref(null)
const showBacktop = ref(false)

//关键词模糊搜索
const searchText = ref('')
const handleSearch = () => {
  if (searchText.value.trim()) {
    router.push({
      path: '/search',
      query: {
        key: searchText.value
      }
    })
  }
}


// 获取新闻数据
const fetchNews = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const response = await fetch('http://localhost:8080/news/getHot');
    if (!response.ok) {
      throw new Error(`HTTP 请求失败，状态码: ${response.status}`);
    }
    
    const data = await response.json();
    if (data.success) {
      newsData.value = data.data;
      filteredNews.value = data.data.slice(0, 8); // 只取前8条
    } else {
      throw new Error('API 返回数据异常');
    }
  } catch (err) {
    console.error('获取新闻失败:', err);
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 页面加载时自动获取数据
onMounted(fetchNews);

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

const handleTabClick = (tab) => {
  const routeMap = {
    home: '/',
    news: '/news',
    people: '/people',
    info: '/info',
    life: '/life'
  }
  
  if (routeMap[tab.paneName]) {
    router.push(routeMap[tab.paneName])
  }
}

const intoDetailPage=async (item) => {
try{
console.log('item',item)
  await router.push({
    path: '/HomePage/DetailPage', query: {id: item,
    }
  })}
  catch (err){
    error.value = err.response?.data?.message || '失败'
  }
}
onMounted(() => {

})

onBeforeUnmount(() => {
  if (observer.value) {
    observer.value.disconnect()
  }
})



// const handleAdminPage = () => {
//   // 此逻辑跳过了注册登陆，直接展示管理员页面，后期需整合调整

//   console.log('管理员登录点击')
// }



</script>

<style scoped>


body {
  margin: 0;
  padding: 0;
}

:deep(.el-container) {
  padding: 0 !important;
  margin: 0 !important;
}

.el-main {
  padding: 0 0.625rem; /* 保留少量内边距 */
  max-width: 100%;
}

.banner-image img {
  display: block; /* 移除图片底部间隙 */
}




/*

————————————————————————————————————————————————————————————————————————————————————————topbar样式——————————————————————————————————————————————————————————————————————————————

 */

.topBar {
  height: 1.875rem;
  width: 100%;
  background-color: #b6daff;
}

/*

————————————————————————————————————————————————————————————————————————————————————————标题样式——————————————————————————————————————————————————————————————————————————————

 */

/* 固定头部样式 */
.fixed-header {
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在最上层 */
  width: 100% !important;
}

/* 占位元素样式 (根据您实际的header高度调整) */
.header-placeholder {
  height: 8.125rem; /* topBar(1.875rem) + headerContent(6.25rem) */
}

/* 标题区域样式 */
.customHeader {
  border-radius: 5%;
  background-color: #ffffff; /* 背景眼色 */
  color: rgb(7, 0, 0); /* 文字颜色 */
  padding: 0 1.25rem;
  height: 7.5rem;
  display: flex;
  align-items: center;
  flex-direction: column; /* 改为垂直布局 */
  box-shadow:
    0 0.25rem 0.5rem rgba(0, 0, 0, 0.1),
    0 0.5rem 1rem rgba(0, 0, 0, 0.1),
    0 0.75rem 1.5rem rgba(0, 0, 0, 0.1); 
    /* 多层叠加阴影，营造立体感 */
}

/* 标题内容样式 */
.headerContent {
  width: 100%;
  height: 20rem;
  display: flex;
  justify-content: space-between; /* 改为左右布局 */
  align-items: center;

}

/* logo样式 */
.logo {
  margin-left: 1.5rem;
  height: 4rem;
  width: auto;
  object-fit: contain;
}

/* 标题容器 */
.titleWrapper {
  display: flex;
  flex-direction: column;
}

/* 主标题样式 */
.mainTitle {
  font-size: 2.2rem;
  font-weight: bold;
  color: #000;
}

/* News文字样式 */
.newsText {
  margin-left: 0.3125rem;
}

/* 副标题样式 */
.subTitle {
  font-size: 1rem;
  color: #409eff; /* Element Plus 主蓝色 */
}

/* 分割线 */
.headerDivider {
  height: 4rem;
  width: 0.0625rem;
  background-color: #c9d5f1;
}

/* 新增左侧容器 */
.headerLeft {
  display: flex;
  align-items: center;
  gap: 0.9375rem;
}

/* 右侧搜索框样式 */
.headerRight {
  width: 17.5rem;
  margin-left: auto;
}

/* 输入框样式 */
.searchInput {
  :deep(.el-input__inner) {
    height: 2.5rem;
    line-height: 2.5rem;
    font-size: 1rem;
    padding: 0 0.9375rem;
    /* 确保输入区域可点击 */
    pointer-events: auto;
    cursor: text;
  }

  :deep(.el-input__wrapper) {
    /* 移除可能遮挡的样式 */
    overflow: visible;
  }
}

.search-icon {
  width: 1.25rem;
  height: 1.25rem;
  object-fit: contain;
}

.headerRightGroup {
  display: flex;
  align-items: center;
  gap: 1.25rem;
}

/* 管理员区域样式优化 */
.adminArea {
  display: flex;
  align-items: center;
  gap: 0.5rem; /* 缩小间距 */
  margin-left: 0.9375rem; /* 与搜索框的间距 */
}

/* 管理员按钮样式优化 */
.adminBtn {
  font-size: 1.125rem; /* 调整为0.875rem */
  font-weight: 600; /* 加粗 */
  letter-spacing: normal;
  padding: 0.4375rem 0.9375rem; /* 缩小内边距 */
  border-radius: 0.25rem;
  background-color: #3589dc; /* Element主色 */
  color: white;
  transition: all 0.3s;
}

.aiChatBtn {
  font-size: 1.125rem; /* 调整为0.875rem */
  font-weight: 600; /* 加粗 */
  letter-spacing: normal;
  padding: 0.4375rem 0.9375rem; /* 缩小内边距 */
  border-radius: 0.25rem;
  background-color: #3589dc; /* Element主色 */
  color: white;
  transition: all 0.3s;
}


.adminBtn:hover {
  background-color: #66b1ff; /* 悬停颜色 */
  transform: translateY(-0.0625rem); /* 轻微上浮效果 */
}

/* 管理员Logo样式优化 */
.adminLogo {
  width: 1.75rem;
  height: 1.75rem;
  object-fit: contain;
  border-radius: 50%; /* 圆形Logo */
  border: 0.0625rem solid #e6e6e6; /* 浅色边框 */
  padding: 0.125rem; /* 内边距 */
  background-color: white; /* 白色背景 */
  box-shadow: 0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.1); /* 轻微阴影 */
}

/*

————————————————————————————————————————————————————————————————————————————————————————导航栏样式——————————————————————————————————————————————————————————————————————————————

 */

/* 导航栏容器 */

/* 导航栏区域样式 */
.customTabs {
  margin-top: 1.25rem;
}

/* 标签样式 */
.customTabs :deep(.el-tabs__item) {
  font-size: 1.1875rem;
  color: #606266;
  padding: 0 1.25rem;
  height: 2.5rem;
  line-height: 2.5rem;
}

/* 被选中标签样式 */
.customTabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: bold;
}

/* 下划线样式 */
.customTabs :deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 0.1875rem;
}

/* 标签栏底部边框 */
.customTabs :deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 0.0625rem solid #e4e7ed;
}



.custom-backtop {
  position: fixed;
  right: 1.875rem;
  bottom: 6.25rem;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  background-color: var(--el-color-primary);
  color: rgb(251, 251, 251);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 9999;
  box-shadow: var(--el-box-shadow-light);
}


/* 
------------新闻卡片----------
*/

.news-container {
  margin-left: 5%;
  max-width: 90%;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  font-size: 1.2rem;
}

.error {
  color: #ff6b6b;
}

.news-list {

  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 关键改动 */
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  width: 100%; /* 确保占满父容器宽度 */
}

.news-item {
  margin-left: 5%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.news-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.news-image {
  height: 200px;
  overflow: hidden;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.news-item:hover .news-image img {
  transform: scale(1.05);
}

.no-image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.news-content {
  padding: 15px;
}

.news-content h2 {
  margin: 0 0 10px;
  font-size: 1.2rem;
  color: #222;
}

.summary {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.8rem;
  color: #888;
}

.time {
  margin-right: 10px;
}

.views {
  color: #ff6b6b;
}
</style>
